package org.budo.redis.jdbc.driver;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.budo.jdbc.driver.AbstractBudoJdbcConnection;
import org.budo.jdbc.driver.parser.SqlStatementParser;
import org.budo.jdbc.driver.statement.JdbcStatement;
import org.budo.redis.jdbc.driver.executor.RedisStatementExecutor;

import lombok.Getter;
import lombok.Setter;

/**
 * @author lmw
 */
@Getter
@Setter
public class BudoRedisJdbcConnection extends AbstractBudoJdbcConnection {
    private SqlStatementParser statementParser;

    private RedisStatementExecutor statementExecutor;

    /**
     * 创建Statement
     */
    @Override
    public Statement createStatement() throws SQLException {
        BudoRedisJdbcStatement statement = new BudoRedisJdbcStatement();
        statement.setConnection(this);
        return statement;
    }

    /**
     * 解析SQL并创建PreparedStatement
     */
    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        JdbcStatement redisStatement = this.getStatementParser().parse(sql);

        BudoRedisJdbcPreparedStatement preparedStatement = new BudoRedisJdbcPreparedStatement();
        preparedStatement.setJdbcStatement(redisStatement);
        preparedStatement.setConnection(this);
        return preparedStatement;
    }

    @Override
    public void close() throws SQLException {
        this.getStatementExecutor().close();
        super.close();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return new BudoRedisJdbcDatabaseMetaData();
    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return true;
    }

    @Override
    public int getHoldability() throws SQLException {
        return ResultSet.CLOSE_CURSORS_AT_COMMIT;
    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return Connection.TRANSACTION_NONE;
    }

    @Override
    public void clearWarnings() throws SQLException {}

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {}

    @Override
    public String toString() {
        return super.toString() + ", statementExecutor=" + statementExecutor + ", statementParser=" + this.statementParser;
    }
}